import { ColumnProps } from "@/components/ProTable/interface";
import { ElForm } from "element-plus";
import { defineComponent } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import "./../alarm.scss";
import { addDeviceAlarm, getDeviceAlarmConfig } from "@/api/modules/iot/alarm";
import { useRoute } from "vue-router";
import { showTips, confirm } from "@/utils/util";
import { alarmParam } from "@/utils/constants";
export default defineComponent({
	props: {
		sn: String,
		title: String,
		sensorKey: {
			type: String,
			default() {
				return "";
			}
		}
	},
	emits: [],
	setup(props, { expose }) {
		const route = useRoute();
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		let configFormData = reactive<any>({
			//告警类型
			alarmType: "",
			//自动处理
			autoDone: false,
			//设备告警
			devCustomWarn: true,
			//是否故障
			isError: 0,
			//阈值上线
			threshold: null,
			//触发方式
			triggerType: 2,
			//越上下线
			warningDlimit: null,
			//越下限
			warningElimit: null,
			//越上限
			warningUlimit: null,
			//告警级别
			warningLevel: 1,
			//告警模式
			warningMode: 1,
			//设备告警=0、平台告警=1
			warningType: 1,
			//告警原因
			alarmReason: null,
			//处理意见
			suggestion: null
		});
		const formRules = ref<any>({});
		const tableRecords = ref<any[]>([]);
		watchEffect(() => {
			if (configFormData.warningMode == 1) {
				formRules.value = {
					warningUlimit: [{ required: true, message: "请设置上限阈值", trigger: "change" }]
				};
				configFormData.warningDlimit = "";
				configFormData.warningElimit = "";
			} else if (configFormData.warningMode == 2) {
				formRules.value = {
					// alarmType: [{ required: true, message: "请设置告警类型", trigger: "change" }],
					warningDlimit: [{ required: true, message: "请设置下限阈值", trigger: "change" }]
				};
				configFormData.warningUlimit = "";
				configFormData.warningElimit = "";
			} else if (configFormData.warningMode == 3) {
				formRules.value = {
					// alarmType: [{ required: true, message: "请设置告警类型", trigger: "change" }],
					warningUlimit: [{ required: true, message: "请设置上限阈值", trigger: "change" }],
					warningDlimit: [{ required: true, message: "请设置下限阈值", trigger: "change" }]
				};
				configFormData.warningElimit = "";
			} else if (configFormData.warningMode == 4) {
				formRules.value = {
					// alarmType: [{ required: true, message: "请设置告警类型", trigger: "change" }],
					warningElimit: [{ required: true, message: "请设置报警阈值", trigger: "change" }]
				};
				configFormData.warningDlimit = "";
				configFormData.warningUlimit = "";
			} else {
				configFormData.warningElimit = "";
				configFormData.warningDlimit = "";
				configFormData.warningUlimit = "";
			}
			formRules.value.alarmType = [
				{ required: true, message: "请设置告警名称", trigger: "change" },
				{
					validator: (rule: any, value: any, callback: any) => {
						if (!isModify.value && tableRecords.value.find(item => item.alarmType == value)) {
							callback(new Error("告警名称已存在"));
						} else {
							callback();
						}
					},
					trigger: "blur"
				}
			];
		});
		const addList = () => {
			(formRef.value as FormInstance).validate(async valid => {
				if (!valid) {
					return;
				}
				configFormData.threshold = configFormData.warningElimit;
				if (isModify.value) {
					tableRecords.value[currtentRowIndex.value] = configFormData;
				} else {
					tableRecords.value.push(JSON.parse(JSON.stringify(configFormData)));
				}
				configFormData.warningDlimit = parseInt(configFormData.warningDlimit);
				configFormData.warningUlimit = parseInt(configFormData.warningUlimit);
				configFormData.warningElimit = parseInt(configFormData.warningElimit);
				saveDeviceAlarm();
			});
		};
		const saveDeviceAlarm = async () => {
			tableRecords.value = tableRecords.value.map((item: any) => {
				item.name = props.title || tableRecords.value[0].name;
				return item;
			});
			let { code } = await addDeviceAlarm({
				sn: props.sn || route.query.sn,
				key: props.sensorKey,
				warning: tableRecords.value
			});
			let ok = showTips(code, "告警配置");
			if (ok) {
				(formRef.value as FormInstance).resetFields();
				// resetForm();
				proTable.value.getTableList();
				isModify.value = false;
				currtentRowIndex.value = "";
			}
		};

		const tempBtnList = reactive([
			{ path: "staging", title: "保存", type: "primary" },
			{ path: "reset", title: "重置" }
		]);
		const buttonsList = reactive([
			{ path: "del", title: "删除", type: "danger" },
			{ path: "detail", title: "编辑", type: "primary" }
		]);
		const dicts = reactive({
			...alarmParam
		});
		//是否是编辑
		const isModify = ref(false);
		const currtentRowIndex = ref();
		const handerBtn = async (fn: string, row: any) => {
			switch (fn) {
				case "del":
					confirm({ content: "删除后无法找回，确定删除当前选择的记录？" }).then((flag: any) => {
						if (flag) {
							tableRecords.value.splice(row.rowIndex, 1);
							saveDeviceAlarm();
						}
					});
					break;
				case "staging":
					addList();
					break;
				case "detail":
					currtentRowIndex.value = row.rowIndex;
					isModify.value = true;
					for (const key in row.row) {
						configFormData[key] = row.row[key];
					}
					break;
				case "reset":
					(formRef.value as FormInstance).resetFields();
					isModify.value = false;
					currtentRowIndex.value = "";
					break;
			}
		};
		const proTable = ref<any>();
		const columns: ColumnProps[] = [
			// { type: "selection", fixed: "left", width: "auto" },
			{ prop: "alarmType", label: "告警类型" },
			{ prop: "autoDone", label: "自动处理" },
			{ prop: "isError", label: "是否故障" },
			{ prop: "triggerType", label: "触发方式" },
			{ prop: "warningElimit", label: "告警阈值" },
			{ prop: "warningLevel", label: "告警级别" },
			{ prop: "warningMode", label: "告警模式" },
			{ prop: "operation", label: "操作", fixed: "right", width: 130 }
		];
		const alarmId = ref();
		const dataCallback = (data: any) => {
			tableRecords.value = data[0]?.warning || [];
			alarmId.value = data[0]?.id || "";
			return {
				datalist: data[0]?.warning || []
				// total: data.total || 0
				// pageIndex: data.current,
				// pageSize: data.size
			};
		};
		const getTableList = async () => {
			return getDeviceAlarmConfig({ sn: props.sn || route.query.sn, key: props.sensorKey });
		};
		expose({});
		return () => {
			return (
				<div class="alarm-config-detail">
					<el-form ref={formRef} rules={formRules} label-width="100px" model={configFormData} validate-on-rule-change={false}>
						<div class="grid grid-cols-3">
							<el-form-item label="告警名称" prop="alarmType" class="col-span-1">
								<el-input v-model={configFormData.alarmType} placeholder="请输入告警名称" />
							</el-form-item>
							<el-form-item label="告警级别" prop="warningLevel" class="col-span-1">
								<el-select v-model={configFormData.warningLevel}>
									{Object.values(dicts.warningLevel).map(item => {
										return <el-option value={item.value} label={item.label}></el-option>;
									})}
								</el-select>
							</el-form-item>
						</div>
						<div class="grid grid-cols-3">
							<el-form-item label="告警模式" prop="warningMode" class="col-span-1">
								<el-select v-model={configFormData.warningMode}>
									{Object.values(dicts.warningMode).map(item => {
										return <el-option value={item.value} label={item.label}></el-option>;
									})}
								</el-select>
							</el-form-item>
							{configFormData.warningMode == 5 ? null : (
								<>
									{configFormData.warningMode == 1 || configFormData.warningMode == 3 ? (
										<el-form-item label="上限阈值" prop="warningUlimit" class="col-span-1">
											<el-input v-model={configFormData.warningUlimit} placeholder="告警上限阈值" type="number" />
										</el-form-item>
									) : null}
									{configFormData.warningMode == 2 || configFormData.warningMode == 3 ? (
										<el-form-item label="下限阈值" prop="warningDlimit" class="col-span-1">
											<el-input v-model={configFormData.warningDlimit} placeholder="告警下限阈值" type="number" />
										</el-form-item>
									) : null}
									{configFormData.warningMode == 4 ? (
										<el-form-item label="报警阈值" prop="warningElimit" class="col-span-1">
											<el-input v-model={configFormData.warningElimit} placeholder="告警阈值" type="number" />
										</el-form-item>
									) : null}
								</>
							)}
						</div>
						<div class="grid grid-cols-3">
							<el-form-item label="是否故障" prop="" class="col-span-1">
								<el-radio-group v-model={configFormData.isError}>
									{Object.values(dicts.isError).map(item => {
										return <el-radio label={item.value}>{item.label}</el-radio>;
									})}
								</el-radio-group>
							</el-form-item>
							<el-form-item label="自动处理" prop="" class="col-span-1">
								<el-radio-group v-model={configFormData.autoDone}>
									{Object.values(dicts.autoDone).map(item => {
										return <el-radio label={item.value}>{item.label}</el-radio>;
									})}
								</el-radio-group>
							</el-form-item>
							<el-form-item label="触发方式" prop="" class="col-span-1">
								<el-radio-group v-model={configFormData.triggerType}>
									{Object.values(dicts.triggerType).map(item => {
										return <el-radio label={item.value}>{item.label}</el-radio>;
									})}
								</el-radio-group>
							</el-form-item>
						</div>
						<el-form-item label="故障原因" prop="alarmReason" class="col-span-1">
							<el-input type="textarea" v-model={configFormData.alarmReason} placeholder="产生故障的原因" />
						</el-form-item>
						{dicts.autoDone.auto.value == configFormData.autoDone ? (
							<el-form-item label="处理意见" prop="suggestion" class="col-span-1">
								<el-input type="textarea" v-model={configFormData.suggestion} placeholder="产生故障处理意见" />
							</el-form-item>
						) : null}
						{/* <el-form-item>
							<el-button type="primary">暂存</el-button>
							<el-button type="primary">提交</el-button>
						</el-form-item> */}
					</el-form>

					<div class="mt-4 ignore-search-split">
						<ProTable
							showSearch={false}
							ref={proTable}
							columns={columns}
							requestApi={getTableList}
							dataCallback={dataCallback}
							pagination={false}
						>
							{{
								tableHeader: (scope: any) => {
									return tempBtnList?.map((item: any) => {
										return (
											<el-button class={`iconfont ${item.icon}`} onClick={() => handerBtn(item.path, scope)} type={item.type}>
												{item.title}
											</el-button>
										);
									});
								},
								alarmType: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => handerBtn("detail", scope)}>
											{scope.row.alarmType}
										</el-link>
									);
								},
								warningMode: (scope: any) => {
									return Object.values(dicts.warningMode).find(item => item.value == scope.row.warningMode)?.label;
								},
								warningLevel: (scope: any) => {
									return Object.values(dicts.warningLevel).find(item => item.value == scope.row.warningLevel)?.label;
								},
								isError: (scope: any) => {
									return Object.values(dicts.isError).find(item => item.value == scope.row.isError)?.label;
								},
								autoDone: (scope: any) => {
									return Object.values(dicts.autoDone).find(item => item.value == scope.row.autoDone)?.label;
								},
								triggerType: (scope: any) => {
									return Object.values(dicts.triggerType).find(item => item.value == scope.row.triggerType)?.label;
								},
								warningType: (scope: any) => {
									return Object.values(dicts.warningType).find(item => item.value == scope.row.warningType)?.label;
								},
								warningElimit: (scope: any) => {
									if (scope.row.warningMode == 1) {
										return scope.row.warningUlimit;
									} else if (scope.row.warningMode == 2) {
										return scope.row.warningDlimit;
									} else if (scope.row.warningMode == 3) {
										return scope.row.warningUlimit + "~" + scope.row.warningDlimit;
									} else if (scope.row.warningMode == 4) {
										return scope.row.warningElimit;
									}
									return Object.values(dicts.triggerType).find(item => item.value == scope.row.triggerType)?.label;
								},
								operation: (scope: any) => {
									return buttonsList.map((item: any) => {
										return (
											<el-link class={`iconfont ${item.icon}`} onClick={() => handerBtn(item.path, scope)} type={item.type}>
												{item.title}
											</el-link>
										);
									});
								}
							}}
						</ProTable>
					</div>
				</div>
			);
		};
	}
});
